<?php
namespace app\app\controller\v1;
use app\app\util\BlockUtils;
use app\app\util\PointUtils;
use think\Db;
use app\app\util\OnlineUtils;
use app\app\model\HistoryModel;
use app\app\model\UsersModel;
use app\app\model\BlockModel;
use app\app\model\FightModel;
use app\app\model\CardModel;

class UserController extends BaseController{

    /**
     * [getUserInfo 获取个人信息]
     * @return [json] [description]
     */
    public function getUserInfo()
    {
        $user_id = OnlineUtils::getUserIdBySid();
        $user    = Db::name('users')->field('id,nickname,avatar_url,fee,points,is_new')->where('id','eq',$user_id)->where('status','eq',1)->find();
        $user['fee'] = $user['fee']/100;
        //查询今天是否签到
        $start = date('Y-m-d',time())." 00:00:01";
        $end   = date('Y-m-d',time())." 23:59:59";
        $start_times = strtotime($start);
        $end_times   = strtotime($end);
        $sign  = Db::name('user_sign')->where('user_id','eq',$user_id)->where('create_time','between',[$start_times,$end_times])->find();
        if( $sign ){
            $user['is_sign'] = 1;
        }else{
            $user['is_sign'] = 0;
        }
        //查询昨天是否签到
        $start = date('Y-m-d',time())." 00:00:01";
        $end   = date('Y-m-d',time())." 23:59:59";
        $start_time = strtotime($start)-24*60*60;
        $end_time   = strtotime($end)-24*60*60;
        $sign_1     = Db::name('user_sign')->where('user_id','eq',$user_id)->where('create_time','between',[$start_time,$end_time])->find();
        if( !$sign_1 ){
            if( $sign ){
                //今日已签
            }else{
                //昨天没签,断签
                $arr = Db::name('sign')->where('user_id','eq',$user_id)->find();
                Db::query('update a_sign set status=0,sign_time=0 where id='.$arr['id']);
            }
        }
        //查询连续签到
        $signs = Db::name('sign')->where('user_id','eq',$user_id)->find();
        $user['sign_times'] = $signs['status'];
        return jsonReturn(200,'success',$user);
    }


    /**
     * [resetFreeNumber 定时任务,重置免费分享与投票次数]
     * @return [type] [description]
     */
    public function resetFreeNumber()
    {
        Db::query('update a_users set chance = 2,free_share = 3,block_share = 0,luck = 1,answers_num = 0 where status=1');
        $user = Db::name('users')->field('id,points')->select();
        foreach($user as $k => $v){
            PointUtils::foundUserPoint($v['id'],$v['points']);
        }
        return jsonReturn(200,'success');
    }


    /**
     * 分享赚卡片
     */
   public function share(){
        $user_id = OnlineUtils::getUserIdBySid();
        //查询是否有次数
        $users = new UsersModel();
        $user  = $users->getOne($user_id);
        if( $user && $user['free_share'] <=0 ){
            return jsonReturn(402,'已达每日分享次数上限,无法获得奖励');
        }
        //分享次数减1
        $users->updateFree($user_id);
       //抽卡数组
       $prize_arr = array(
           array('id'=>1,'prize'=>'程长庚','v'=>1),
           array('id'=>2,'prize'=>'陈独秀','v'=>1),
           array('id'=>3,'prize'=>'陈延年','v'=>5),
           array('id'=>4,'prize'=>'陈乔年','v'=>5),
           array('id'=>5,'prize'=>'邓稼先','v'=>5),
           array('id'=>6,'prize'=>'黄镇','v'=>5),
           array('id'=>7,'prize'=>'赵朴初','v'=>5),
           array('id'=>8,'prize'=>'张恨水','v'=>5),
           array('id'=>9,'prize'=>'章伯钧','v'=>5),
           array('id'=>10,'prize'=>'朱光潜','v'=>5),
           array('id'=>11,'prize'=>'严凤英','v'=>5),
           array('id'=>12,'prize'=>'黄绮','v'=>5),
           array('id'=>13,'prize'=>'马兰','v'=>5),
           array('id'=>14,'prize'=>'韩再芬','v'=>5),
           array('id'=>15,'prize'=>'田海蓉','v'=>5),
           array('id'=>16,'prize'=>'夏菊花','v'=>5),
           array('id'=>17,'prize'=>'王文银','v'=>5),
           array('id'=>18,'prize'=>'阎焱','v'=>5),
           array('id'=>19,'prize'=>'陈奇星','v'=>8),
           array('id'=>20,'prize'=>'李斌','v'=>10)
       );
       // 抽卡
       foreach ($prize_arr as $key => $val) {
           $arr[$val['id']] = $val['v'];
       }
       $id = get_rand($arr); //根据概率获取奖项id
        //取出卡片
        $history = new HistoryModel();
        $history->user_id = $user_id;
        try{
            $data = $history->getOne($id);
        }catch (Exception $e){
            return jsonReturn(402,'分享失败');
        }
        //redis每日分享次数
        $share = BlockUtils::getShare($user_id);
        //更新数据
        $today = date('Y-m-d')." 23:59:59";
        $today = strtotime($today);
        $now   = time();
        $overTime = $today - $now;
        $value = $share + 1;
        BlockUtils::setShare($user_id,$value,$overTime);
        return jsonReturn(200,'success',$data);
   }


    /**
     * 用户中心
     */
   public function userCenter(){
       $user_id = OnlineUtils::getUserIdBySid();
       //获取用户信息
       $users = new UsersModel();
       $user  = $users->getOne($user_id);
       $userData = array('nickname'=>$user['nickname'],'avatar_url'=>$user['avatar_url']);
       //语音
       $card = new CardModel();
       $cards= $card->getOne($user_id);
       //获取好友对战模式信息
       $fights = new FightModel();
       $fights->user_id = $user_id;
       $fight = $fights->getFight();
       //通关模式
       $block = new BlockModel();
       $block->user_id = $user_id;
       $block_num = $block->getInfo();
       //获取称号
       $achieve = $block->getAchieve();
       //最高排名
       $rank = BlockUtils::getUserRank($user_id);
       $data = array('max_num'=>$block_num['num'],'rank'=>$rank+1);
       return jsonReturn(200,'success',['fight'=>$fight,'block'=>$data,'user'=>$userData,'card'=>$cards,'achieve'=>$achieve]);
   }

    /**
     * 增加积分
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function addPoint(){
       $user_id = OnlineUtils::getUserIdBySid();
       $point   = input('get.point');
       $user    = PointUtils::getUserPoint($user_id);
       $all_point = $point+$user;
       Db::name('users')->update(array('id'=>$user_id,'points'=>$all_point));
       PointUtils::getUserPoint($user_id,$point);
       $rank    = PointUtils::getPointRank(0,10);
       return jsonReturn(200,'success',['point'=>$all_point,'rank'=>$rank]);
    }

    /**
     * 抽奖
     */
    public function luck(){
        $user_id = OnlineUtils::getUserIdBySid();
        $luck_id = input('post.id') ? input('post.id') : 1;
        $reward  = Db::name('reward')->where('id','eq',$luck_id)->find();
        if( $reward ){
            $user = Db::name('users')->where('id','eq',$user_id)->find();
            if( $user && $user['luck'] >0 ){
                Db::query('update a_users set fee = fee + '.$reward['val'].',luck = 0 where id='.$user_id);
                return jsonReturn(200,'success',$reward['description']);
            }else{
                return jsonReturn(402,'抽奖次数不足');
            }
        }else{
            return jsonReturn(402,'奖品不存在');
        }
    }

    /**
     * 获取转盘
     */
    public function getLuck(){
        $user_id = OnlineUtils::getUserIdBySid();
        $data = Db::name('reward')->field('id,title,concat("'.getConfig('IMG_HEAD').'",img) img,rate')->select();
        $user = Db::name('users')->field('luck')->where('id','eq',$user_id)->find();
        return jsonReturn(200,'success',['reward'=>$data,'luck'=>$user['luck']]);
    }

    /**
     * 获取用户信息
     */
    public function getUserDetails(){
        $user_id = OnlineUtils::getUserIdBySid();
        $id = input('get.id')?input('get.id'):0;
        $user = Db::name('users')->field('nickname,avatar_url')->where('id','eq',$id)->where('status','eq',1)->find();
        $card = Db::name('card')->where('user_id','eq',$id)->where('status','eq',1)->find();
		$card['audio'] = 'https://'.$_SERVER['HTTP_HOST'].'/uploads/audio/'.str_replace('\\','/',$card['audio']);
        return jsonReturn(200,'success',['user'=>$user,'card'=>$card]);
    }

    /**
     * 获取历史人物卡片
     */
    public function getHistory(){
        $user_id = OnlineUtils::getUserIdBySid();
        $data = Db::name('history')->field('a.id,a.name,concat("'.getConfig('IMG_HEAD').'",a.img) img,b.num')->alias('a')->join('user_history b','a.id=b.h_id','left')->where('b.user_id','eq',$user_id)
            ->order('b.num desc')->select();
        $arr  = array();
        foreach($data as $k => $v){
            if($v['num'] > 0){
                $arr[] = $v['id'];
            }
        }
        if( count($arr) == 20 ){
            //更改状态
            Db::query('update a_users set is_collect = 1 where id ='.$user_id);
        }else{
            Db::query('update a_users set is_collect = 0 where id ='.$user_id);
        }
        $user = Db::name('users')->field('is_collect,is_charge')->where('id','eq',$user_id)->find();
        return jsonReturn(200,'success',['history'=>$data,'user'=>$user]);
    }

    /**
     * 赠送历史人物卡片
     */
    public function giveHistory(){
        $user_id = OnlineUtils::getUserIdBySid();
        //赠送的卡的Id
        $id = input('post.id')?input('post.id'):0;
        //查询卡存在并且数量是否大于0
        $card = Db::name('user_history')->alias('a')->field('a.num,b.name,concat("'.getConfig('IMG_HEAD').'",img) img')->join('history b',
            'a.h_id=b.id','left')->where('b.id','eq',$id)->where('a.user_id','eq',$user_id)->find();
        //
        if( $card && $card['num'] > 1 ){
            //插入记录
            Db::name('share')->insert(array('user_id'=>$user_id,'h_id'=>$id,'create_time'=>time()));
            Db::query('update a_user_history set num = num - 1 where user_id='.$user_id.' and h_id='.$id);
            return jsonReturn(200,'success');
        }else{
            return jsonReturn(402,'卡片数量不足');
        }
    }


    /**
     * 领取卡片
     */
    public function recive(){
        $user_id = OnlineUtils::getUserIdBySid();
        $id  = input('post.id')?input('post.id'):0;
        $uid = input('post.user_id')?input('post.user_id'):0;
        if( $id == 0 || $uid == 0 ){
            return jsonReturn(402,'fail');
        }
        //领取卡片
        $start = strtotime(date('Y-m-d')." 00:00:01");
        $end   = strtotime(date('Y-m-d')." 23:59:59");
        $give  = Db::name('give')->where('user_id','eq',$uid)->where('h_id','eq',$id)->where('recive_id','eq',$user_id)
            ->where('create_time','between',[$start,$end])->find();
//        return jsonReturn(200,'success',$give);
        if( !$give ){
            //查询分享记录
            $share = Db::name('share')->where('user_id','eq',$uid)->where('h_id','eq',$id)->where('num','eq',1)->find();
            //设置为已领取
            Db::name('share')->update(array('id'=>$share['id'],'num'=>0));
            //持卡数+1
            Db::query('update a_user_history set num = num + 1 where user_id='.$user_id.' and h_id ='.$id);
            //插入记录
            Db::name('give')->insert(array('user_id'=>$uid,'recive_id'=>$user_id,'h_id'=>$id,'create_time'=>time()));
            return jsonReturn(200,'success');
        }else{
            return jsonReturn(402,'今日已领取过相同卡片');
        }

    }

    /**
     * 同意求赠
     */
    public function agreeGive(){
        $user_id = OnlineUtils::getUserIdBySid();
        $id  = input('post.id')?input('post.id'):0;
        $uid = input('post.user_id')?input('post.user_id'):0;
        if( $id == 0 || $uid == 0 ){
            return jsonReturn(402,'fail');
        }
        $start = strtotime(date('Y-m-d')." 00:00:01");
        $end   = strtotime(date('Y-m-d')." 23:59:59");
        $share = Db::name('give')->where('user_id','eq',$user_id)->where('recive_id','eq',$uid)->where('h_id','eq',$id)
            ->where('create_time','between',[$start,$end])->find();
        if( !$share ){
            //插入记录
            Db::name('give')->insert(array('user_id'=>$user_id,'recive_id'=>$uid,'h_id'=>$id,'create_time'=>time()));
            //卡片-1
            Db::query('update a_user_history set num = num - 1 where user_id='.$user_id.' and h_id='.$id);
            //卡片+1
            Db::query('update a_user_history set num = num + 1 where user_id='.$uid.' and h_id='.$id);
            return jsonReturn(200,'success');
        }else{
            return jsonReturn(402,'今日已赠送此卡');
        }
    }

    /**
     * 集齐卡片兑换奖励
     */
    public function chargeReward(){
        $user_id = OnlineUtils::getUserIdBySid();
        $users = new UsersModel();
        $user  = $users->getOne($user_id);
        if($user['is_collect'] == 0){
            return jsonReturn(402,'卡片未集齐，无法兑换');
        }else{
            $charge = Db::name('charge')->where('user_id','eq',$user_id)->find();
            if($charge){
                return jsonReturn(402,'奖励只能兑换一次哦');
            }else{
                Db::name('charge')->insert(array('user_id'=>$user_id,'create_time'=>time()));
                //加钱
                Db::query('update a_users set is_charge = 1,fee = fee +'.config('CHARGE').' where id='.$user_id);
                return jsonReturn(200,'success',['fee'=>config('CHARGE')/100]);
            }
        }

    }


    /**
     * 更改new
     */
    public function isNew(){
        $user_id = OnlineUtils::getUserIdBySid();
        Db::query('update a_users set is_new = 0 where id='.$user_id);
        return jsonReturn(200,'success');
    }

}